package com.shxy.controller;

import com.shxy.common.ApiResult;
import com.shxy.common.ResultCode;
import com.shxy.controller.ui.EmployeeBean;
import com.shxy.entity.Employee;
import com.shxy.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 员工信息管理控制器
 */
@RestController
@RequestMapping("/v2/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;

    /*员工基本信息管理*************************************************************************/

    /**
     * 添加新员工信息
     * @param employee
     * @return
     */
    @PostMapping("/add")
    public ApiResult add(@Validated(value = {EmployeeBean.Add.class}) @RequestBody EmployeeBean employee) {
        // 1、根据身份证号确定该员工是否已经存在
        if(employeeService.existsOfIdCard(employee.getIdCard())) {
            return ApiResult.fail(ResultCode.USER_ACCOUNT_ALREADY_EXIST);
        }
        // 2、保存员工信息
        employeeService.create(employee);
        return ApiResult.success();
    }

    /**
     * 更新员工信息
     * @return
     */
    @PostMapping("/update")
    public ApiResult update(@Validated(value = {EmployeeBean.Update.class})@RequestBody EmployeeBean employee) {
        // 1、判断员工是否存在
        if(!employeeService.existsOfId(employee.getId())) {
            return ApiResult.fail(ResultCode.USER_ACCOUNT_NOT_EXIST);
        }
        // 2、修改员工信息
        employeeService.update(employee);
        return ApiResult.success();
    }

    /**
     * 查询
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/query")
    public ApiResult query(@RequestBody EmployeeBean employee,
                           @RequestParam(required = false, defaultValue = "1") int page,
                           @RequestParam(required = false, defaultValue = "10") int size) {
        Page<Employee> employees = employeeService.query(employee, page, size);
        return ApiResult.success(employees);
    }

    @GetMapping("/import")
    public ApiResult importEmployees() {
        List<Employee> employees = employeeService.importFromBase();
        return ApiResult.success(employees);
    }
}
